﻿using System;   
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using AmorCanino.Common;

namespace AmorCanino.Web.Models.Services
{
    public class MailingService : BaseService, IMailingService
    {
        public void SendMessage(Models.Message message)
        {
            string contactEmail = ConfigurationHandler.ContactEmail;

            if (contactEmail != null)
            {
                try
                {
                    var mail = new MailMessage();
                    var SmtpServer = new SmtpClient(ConfigurationHandler.SMTPServer);

                    if (ConfigurationHandler.SMTPUserCredentials)
                    {
                        SmtpServer.Credentials = new System.Net.NetworkCredential(
                            ConfigurationHandler.EmailUsername,
                            ConfigurationHandler.EmailPassword);
                    }

                    mail.From = new MailAddress(message.FromEmail);
                    mail.To.Add(contactEmail);
                    mail.Subject = message.Title;
                    mail.Body = message.Body;
                    SmtpServer.Send(mail);
                    return;
                }
                catch (Exception ex)
                {
                    Logger.WriteLog(new Common.Logger.LogEntry()
                    {
                        Message = "Se ha producido un error al intentar enviar un email de contacto\n" + ex.Message
                    });
                    goto LogMessage;
                }
            }

        LogMessage:
            Logger.LogDetail = Common.Logger.LogDetails.Information;
            Logger.LogLevel = Common.Logger.LogLevels.Information;
            Logger.WriteLog(new Common.Logger.LogEntry()
            {
                Application = "Contact page",
                Message = string.Format("{0} - {1}\n{2}", message.Title, message.FromEmail, message.Body)
            });

        }
    }
}